package cc.liyinghao.springsecuritydemo.pojo.bo;

import cc.liyinghao.springsecuritydemo.pojo.User;
import cn.hutool.core.util.StrUtil;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * SpringSecurity需要的UserDetails封装类
 */
@Data
public class UserDetail implements UserDetails {

    //用户
    private User user;
    //角色
    private Set<String> roles;
    //权限
    private Set<String> permissions;


    public UserDetail(User user, Set<String> roles, Set<String> permissions) {
        this.user = user;
        this.roles = roles;
        this.permissions = permissions;
    }

    //返回权限信息
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
//        return permissions.stream().filter(StrUtil::isNotEmpty)
//                .map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        Set<GrantedAuthority> authorities = new HashSet<>();
        // 添加角色（Spring Security 需要 "ROLE_" 前缀）
        if (roles != null) {
            authorities.addAll(roles.stream()
                    .map(role -> new SimpleGrantedAuthority("ROLE_" + role)) // 确保带 "ROLE_"
                    .collect(Collectors.toSet()));
        }
        // 添加权限
        if (permissions != null) {
            authorities.addAll(permissions.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toSet()));
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
